package com.zjb.demo.common.controller;

import com.google.code.kaptcha.Producer;
import com.zjb.demo.common.config.AppConfig;
import com.zjb.demo.common.constant.CacheConstants;
import com.zjb.demo.common.constant.Constants;
import com.zjb.demo.common.domain.response.AjaxResult;
import com.zjb.demo.common.domain.response.Captcha;
import org.noear.redisx.plus.RedisBucket;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;

import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

/**
 * @author 庄佳彬
 * @since 2023/12/23 22:05
 */
@Controller
public class CaptchaController {
    @Inject
    private RedisBucket redisBucket;
    @Inject
    private AppConfig appConfig;

    @Inject(value = "captchaProducer")
    private Producer producer;

    @Get
    @Mapping("/captchaImage")
    public AjaxResult<Captcha> getCaptcha() {
        var enabled = appConfig.getCaptchaEnabled();
        if (!enabled) {
            return AjaxResult.success(new Captcha());
        }

        var uuid = UUID.randomUUID().toString();
        var verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        var capStr = producer.createText();
        var image = producer.createImage(capStr);

        redisBucket.store(verifyKey, capStr, Constants.CAPTCHA_EXPIRATION);
        var os = new ByteArrayOutputStream();
        try {
            if (image != null) {
                ImageIO.write(image, "jpg", os);
            }
            var img = Base64.getEncoder().encodeToString(os.toByteArray());
            return AjaxResult.success(new Captcha(uuid, img, true));
        } catch (IOException e) {
            return AjaxResult.fail(e.getMessage());
        }
    }
}
